package com.mushiengine.core {
import flash.utils.getDefinitionByName;

import mx.utils.DescribeTypeCache;

import nl.demonsters.debugger.MonsterDebugger;

public class Injector implements IInjector{
    public function Injector() {
    }

    public function injectViaClass(beanClass:Class):* {
       return injectViaInstance(new beanClass());
    }

    internal function injectMetaDataExist(classDesc:XMLList):Boolean {
        if (classDesc.variable.length() == 0) return false;

        for each(var classVar:XML in classDesc.variable) {

            if (classVar.metadata.@name == "Inject") {
                return true;
            }
        }
        return false;
    }

    public function injectViaInstance(beanInstance:*):* {
        var objDesc : XMLList = XMLList(DescribeTypeCache.describeType(beanInstance).typeDescription);

        if (injectMetaDataExist(objDesc)) {
            return workOnInjectMetaData(beanInstance, objDesc);
        } else {
            return beanInstance;
        }
    }

    internal function workOnInjectMetaData(instanceToBeInjected:*, instanceDesc:XMLList):* {
        for each(var classVar:XML in instanceDesc.variable) {
            if (classVar.metadata.@name == "Inject") {
                var injetClass:Class = Class(getDefinitionByName(classVar.@type));
                var objInst:* = new injetClass();
                instanceToBeInjected[classVar.@name] = objInst;
                injectViaInstance(objInst);
            }
        }

        return instanceToBeInjected;
    }


}

}